import React, { useEffect, useRef, useState } from 'react';
import { mockData } from '../utils/mockData';

const HotQA = () => {
  const scrollContainerRef = useRef(null);
  const scrollIntervalRef = useRef(null);
  const [qaList, setQaList] = useState([]);

  useEffect(() => {
    setQaList(mockData.hotQA);
    setupScrollEffect();

    return () => {
      if (scrollIntervalRef.current) {
        clearInterval(scrollIntervalRef.current);
      }
    };
  }, []);

  const setupScrollEffect = () => {
    if (!scrollContainerRef.current) return;

    let scrollPosition = 0;

    const scrollQA = () => {
      if (!scrollContainerRef.current) return;
      
      scrollPosition += 1;
      if (
        scrollPosition >=
        scrollContainerRef.current.scrollHeight - scrollContainerRef.current.clientHeight
      ) {
        scrollPosition = 0;
      }
      scrollContainerRef.current.scrollTop = scrollPosition;
    };

    scrollIntervalRef.current = setInterval(scrollQA, 50);

    // 鼠标悬停暂停滚动
    const handleMouseEnter = () => {
      if (scrollIntervalRef.current) {
        clearInterval(scrollIntervalRef.current);
      }
    };

    const handleMouseLeave = () => {
      scrollIntervalRef.current = setInterval(scrollQA, 50);
    };

    scrollContainerRef.current.addEventListener("mouseenter", handleMouseEnter);
    scrollContainerRef.current.addEventListener("mouseleave", handleMouseLeave);

    return () => {
      if (scrollContainerRef.current) {
        scrollContainerRef.current.removeEventListener("mouseenter", handleMouseEnter);
        scrollContainerRef.current.removeEventListener("mouseleave", handleMouseLeave);
      }
    };
  };

  return (
    <div className="hot-qa-container">
      <div className="hot-qa-header">
        <div className="add">+</div>
      </div>
      
      <div className="hot-qa-content">
        <div 
          ref={scrollContainerRef} 
          className="scroll-container"
        >
          <div className="qa-list">
            {qaList.map((qa, index) => (
              <div key={index} className="qa-item">
                <div className="question">{qa.question}</div>
                <div className="answer">{qa.answer}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

export default HotQA;
